﻿using Cysharp.Threading.Tasks;
using IQIGame.Rendering;
using UnityEngine;
using UnityEngine.UI;

namespace IQIGame.Onigao.Game
{
    public class UIBackgroundAdapter : UITransformAdapter
    {
        private string blurRTName = null;

        bool isInitRawImg = false;
        RawImage m_rawImage;
        RawImage rawImage
        {
            get
            {
                if (!this.isInitRawImg)
                {
                    this.m_rawImage = this.GetComponent<RawImage>();
                    this.isInitRawImg = true;
                }
                return this.m_rawImage;
            }
        }

        /// <summary>
        /// 适配背景RawImage的图片
        /// </summary>
        public async UniTask GenBlurRtAndApply(string rtName, int downSampling = 2)
        {
            if (this.rawImage != null)
            {
                var rt = await RenderBlurUtil.GetBlurTexAsyncReadBack(rtName, GameRender.CameraType.UICamera, downSampling);
                this.blurRTName = rtName;
                this.rawImage.texture = rt;
            }
        }

        private void ReleaseRt()
        {
            if (this.blurRTName != null)
            {
                this.rawImage.texture = null;
                RenderBlurUtil.ReleaseBlurRT(blurRTName);
            }
            this.blurRTName = null;
        }

        public void SetBGRawImageTexture(Texture2D texture)
        {
            if (this.rawImage != null)
            {
                this.ReleaseRt();
                this.rawImage.texture = texture;
            }
        }

        protected override void OnDestroy()
        {
            this.ReleaseRt();
            base.OnDestroy();
        }
    }
}
